import java.util.*;

public class T16_0411 {
    public List<String> topKFrequent(String[] words, int k) {
        List<String> list = new ArrayList<>();
        Map<String,Integer> map = new HashMap<>();
        for (String word : words) {
            if (map.containsKey(word)) {
                map.put(word, map.get(word) + 1);
            } else {
                map.put(word, 1);
            }
        }
        PriorityQueue<Map.Entry<String,Integer>> priorityQueue = new PriorityQueue<>(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if (o1.getValue().compareTo(o2.getValue()) == 0) {
                    return o2.getKey().compareTo(o1.getKey());
                }
                return o1.getValue().compareTo(o2.getValue());
            };
        });

       for ( Map.Entry<String,Integer> entry : map.entrySet()) {
            if (priorityQueue.size() < k) {
                priorityQueue.offer(entry);
            } else {
                Map.Entry<String,Integer> top = priorityQueue.peek();
                if (top.getValue().compareTo(entry.getValue()) == 0) {
                    if (top.getKey().compareTo(entry.getKey()) > 0) {
                        priorityQueue.poll();
                        priorityQueue.offer(entry);
                    }
                }else {
                    if (top.getValue().compareTo(entry.getValue()) < 0) {
                        priorityQueue.poll();
                        priorityQueue.offer(entry);
                    }
                }
            }
       }

        for (int i = 0; i < k; i++) {
            Map.Entry<String,Integer> entry = priorityQueue.poll();
            list.add(entry.getKey());
        }
        Collections.reverse(list);
        return list;
    }
}
